package com.atguigu.dwm.common.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ArrayTypeHandler extends BaseTypeHandler<Long[]> {

    // 从 java对象属性 Long[] 转为数据库的字段 varchar(string)
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long[] parameter, JdbcType jdbcType) throws SQLException {
        //把parameter 转成字符串,用逗号拼接
        String value = Arrays.stream(parameter).map(String::valueOf).collect(Collectors.joining(","));
        ps.setString(i,value);
    }

    //从数据库的字段 varchar 转为 java对象属性 Long[]
    @Override
    public Long[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String stringValue = rs.getString(columnName);

        if(stringValue!=null&&!stringValue.isEmpty()){
            //把字符串转成数组
            String[] split = stringValue.split(",");
            //把数组转成Long[]
            return Arrays.stream(split).map(Long::valueOf).toArray(Long[]::new);
        }
        return new Long[0];
    }

    @Override
    public Long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String stringValue = rs.getString(columnIndex);
        if(stringValue!=null&&!stringValue.isEmpty()){
            //把字符串转成数组
            String[] split = stringValue.split(",");
            //把数组转成Long[]
            return Arrays.stream(split).map(Long::valueOf).toArray(Long[]::new);
        }
        return new Long[0];
    }

    @Override
    public Long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String stringValue = cs.getString(columnIndex);
        if(stringValue!=null&&!stringValue.isEmpty()){
            //把字符串转成数组
            String[] split = stringValue.split(",");
            //把数组转成Long[]
            return Arrays.stream(split).map(Long::valueOf).toArray(Long[]::new);
        }
        return new Long[0];
    }
}
